package com.wjw.java.thread.homework;

import java.util.Scanner;

/**
 * main线程中启动两个线程：A和B
 * A线程循环输出100以内的整数,
 * B线程读取键盘上输入的内容,如果输入的内容为Q,就停止A线程
 */
public class HomeWork1 {
    public static void main(String[] args) {
        //线程A
        A a = new A();
        Thread t1 = new Thread(a,"线程A");

        //线程B
        B b = new B();
        b.setA(a);//线程B中设置线程A,方便满足条件时,停止线程A
        Thread t2 = new Thread(b,"线程B");

        t1.start();
        t2.start();
    }
}
class A implements Runnable{

    private boolean ifLoop = true;//是否循环

    public boolean isIfLoop() {
        return this.ifLoop;
    }

    public void setIfLoop(boolean ifLoop) {
        this.ifLoop = ifLoop;
    }

    @Override
    public void run() {
       while (ifLoop){
           String name = Thread.currentThread().getName();
           //输出100以内的整数
           int result = (int) (Math.random() * 100 + 1);
           try {
               System.out.println(name+":运行中..."+result);
               Thread.sleep(1000);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
    }
}

class B implements Runnable{

    private A a;

    public A getA() {
        return this.a;
    }

    public void setA(A a) {
        this.a = a;
    }

    @Override
    public void run() {
        while (true){
            String name = Thread.currentThread().getName();
            Scanner scanner = new Scanner(System.in);
            System.out.println(name+":请输入一个字母：");
            String input = scanner.next();
            String upperCase = input.toUpperCase();
            System.out.println("输入的字母为："+upperCase);
            if("Q".equals(upperCase)){
                a.setIfLoop(false);//停止A线程
                break;//结束循环
            }
        }

    }
}